package com.hxs.learn.service.core;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.hxs.learn.common.entity.BillSequenceKey;
import com.hxs.learn.common.entity.TreeJson;
import com.hxs.learn.common.page.Page;
import com.hxs.learn.common.page.PageHelper;
import com.hxs.learn.common.page.PageWrapper;
import com.hxs.learn.common.result.Result;
import com.hxs.learn.common.web.LoginInfo;
import com.hxs.learn.constants.core.sql.SqlColConts;
import com.hxs.learn.entity.core.SysRole;
import com.hxs.learn.mapper.core.SysRoleMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author huxinsheng
 * @data 2018-04-24
 */
@Service
public class SysRoleService {
    private Logger logger = LoggerFactory.getLogger(SysRoleService.class);
    private final SysRoleMapper roleMapper;
    private final SysRoleMenuService roleMenuService;
    private final BillService billService;

    @Autowired
    public SysRoleService(SysRoleMapper roleMapper, SysRoleMenuService roleMenuService, BillService billService) {
        this.roleMapper = roleMapper;
        this.roleMenuService = roleMenuService;
        this.billService = billService;
    }

    /**
     * 查询所有
     *
     * @return List<SysRole>
     */
    public List<SysRole> findAllSysRole() {
        return roleMapper.selectList(new EntityWrapper<>(new SysRole()));
    }

    /**
     * 按主键查询
     *
     * @param id 主键id
     * @return SysRole
     */
    public SysRole findById(Serializable id) {
        return roleMapper.selectById(id);
    }

    /**
     * 分页查询
     *
     * @param page    分页对象
     * @param sysRole 分页条件对象
     * @return PageWrapper<SysRole>
     */
    public PageWrapper<SysRole> findSysRolePageData(Page page, SysRole sysRole) {
        return PageHelper.getPageData(roleMapper, page, sysRole);
    }

    /**
     * 按主键删除
     *
     * @param id 主键id
     */
    @Transactional(rollbackFor = Exception.class)
    public Result removeById(Serializable id) {
        roleMapper.deleteById(id);

        return Result.ok();
    }

    /**
     * 保存
     *
     * @param loginUser 登录用户信息
     * @param sysRole   系统角色信息
     */
    @Transactional(rollbackFor = Exception.class)
    public Result save(LoginInfo loginUser, SysRole sysRole) {
        sysRole.setUpdateBy(loginUser.getLoginName());
        sysRole.setUpdateTime(new Date());

        Wrapper<SysRole> wrapper = new EntityWrapper<>();

        if (StringUtils.isEmpty(sysRole.getId())) {
            wrapper.eq(SqlColConts.NAME, sysRole.getName());
        } else {
            wrapper.eq(SqlColConts.NAME, sysRole.getName()).and().ne(SqlColConts.ID, sysRole.getId());
        }

        int count = roleMapper.selectCount(wrapper);

        if (count > 0) {
            return Result.error("角色名称已存在!");
        }

        if (StringUtils.isEmpty(sysRole.getId())) {
            String id = billService.newBillNo(new BillSequenceKey(SqlColConts.KEY_ROLE_ID));

            sysRole.setId(id);
            sysRole.setCreator(loginUser.getLoginName());
            sysRole.setCreateTime(new Date());
            roleMapper.insertAllColumn(sysRole);
        } else {
            roleMapper.updateById(sysRole);
        }

        return Result.ok();
    }

    public Object getRoleTreeJsonData(String name) {
        SysRole rolePojo = new SysRole();

        rolePojo.setName(name);

        List<SysRole> roles = roleMapper.selectList(new EntityWrapper<>(rolePojo));

        if (CollectionUtils.isEmpty(roles)) {
            return null;
        }

        List<TreeJson<Object>> treeJsonList = new ArrayList<>();

        for (SysRole role : roles) {
            TreeJson treeJson = new TreeJson();

            treeJson.setId(role.getId());
            treeJson.setPid(SqlColConts.PID_VALUE);
            treeJson.setName(role.getName());
            treeJson.setData(role);
            treeJson.setSeq(0);
            treeJsonList.add(treeJson);

            List<TreeJson<Object>> menuTreeJson = roleMenuService.getMenuTreeJsonByRoleId(role.getId());

            if (!CollectionUtils.isEmpty(menuTreeJson)) {
                treeJsonList.addAll(menuTreeJson);
            }
        }

        return treeJsonList;
    }

    public List<SysRole> findByUserId(String userId) {
        return roleMapper.selectByUserId(userId);
    }
}


//~ Formatted by Jindent --- http://www.jindent.com
